package com.cloudptt.api.product.func.sys;

import com.cloudptt.api.comm.CommDlg;
import com.cloudptt.api.pjsip.api.SipManager;
import com.cloudptt.api.product.func.IBroadcast;
import com.cloudptt.api.product.func.call.CallAttr;
import com.cloudptt.api.product.func.sys.fsm.SysAgent;
import com.cloudptt.api.product.func.sys.fsm.SysConst;
import com.cloudptt.api.product.func.sys.listener.SysMsgListener;
import com.cloudptt.api.product.log.Log;
import com.cloudptt.api.product.operator.SysOperator;
import com.cloudptt.api.product.res.Resource;
import com.hytera.productsdk.R;
import com.mcptt.config.ConfigCenter;
import com.mcptt.config.body.McxExtensionXml;
import com.mcptt.config.callback.IParserCallback;
import com.mcptt.config.local.SysConfig;
import com.mcptt.config.model.McIdInfo;
import com.mcptt.config.user.profile.UserProfile;
import com.mcptt.db.DBAdapter;
import com.mcptt.db.model.GroupInfo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import java.util.Iterator;
import java.util.List;

public class SysBroadcast extends BroadcastReceiver implements IBroadcast, IParserCallback
{
	private Context ctx = null;
	private SysAgent sysAgent = null;
	//	private AlarmTimer keepLiveTimer = null;
	private SysMsgListener sysMsgListener = null;
	private ConfigCenter configCenter = null;
	private SysConfig config = null;
	private DBAdapter dbAdapter = null;
	private SysOperator operator = null;
//	private int curGoupSize = 0;

	public SysBroadcast(Context ctx, SysAgent sysAgent, ConfigCenter configCenter, SysConfig config, DBAdapter dbAdapter, SysOperator operator)
	{
		Log.debug(this.getClass(), "SysBroadcast");
		this.ctx = ctx;
		this.sysAgent = sysAgent;
		this.configCenter = configCenter;
		this.config = config;
		this.dbAdapter = dbAdapter;
		this.operator = operator;


//		this.ctx.registerReceiver(this, new IntentFilter(SipManager.ACTION_SIP_STACK_CHANGED),SipManager.PERMISSION_USE_SIP,null);
//		this.ctx.registerReceiver(this, new IntentFilter(SipManager.ACTION_SIP_REG),SipManager.PERMISSION_USE_SIP,null);
//		this.ctx.registerReceiver(this, new IntentFilter(SipManager.ACTION_SIP_FOREDETACH),SipManager.PERMISSION_USE_SIP,null);
//		this.ctx.registerReceiver(this, new IntentFilter(SipManager.ACTION_SIP_SVR_RESTART),SipManager.PERMISSION_USE_SIP,null);
//
//		this.ctx.registerReceiver(this, new IntentFilter(SipManager.ACTION_SIP_PUBLISH),SipManager.PERMISSION_USE_SIP,null);
//		this.ctx.registerReceiver(this, new IntentFilter(SipManager.ACTION_SIP_SUBSCRIBE),SipManager.PERMISSION_USE_SIP,null);
//
//		//		this.ctx.registerReceiver(this, new IntentFilter(SipManager.ACTION_NETWORK_CHANGED));
//		this.ctx.registerReceiver(this, new IntentFilter(SipManager.ACTION_SIP_MESSAGE_SYS),SipManager.PERMISSION_USE_SIP,null);
//		this.ctx.registerReceiver(this, new IntentFilter(SipManager.ACTION_SIP_KEEPALIVE),SipManager.PERMISSION_USE_SIP,null);
//		this.ctx.registerReceiver(this, new IntentFilter(SipManager.ACTION_SYS_NOTIFY),SipManager.PERMISSION_USE_SIP,null);
//		this.ctx.registerReceiver(this, new IntentFilter(SipManager.ACTION_SIP_NOTIFY_XCAP_DIFF),SipManager.PERMISSION_USE_SIP,null);

		IntentFilter filter = new IntentFilter();
		filter.addAction(SipManager.ACTION_SIP_STACK_CHANGED);
		filter.addAction(SipManager.ACTION_SIP_REG);
		filter.addAction(SipManager.ACTION_SIP_UNREG);
		filter.addAction(SipManager.ACTION_SIP_FOREDETACH);
		filter.addAction(SipManager.ACTION_SIP_SVR_RESTART);

		filter.addAction(SipManager.ACTION_SIP_PUBLISH);
		filter.addAction(SipManager.ACTION_SIP_SUBSCRIBE);

		filter.addAction(SipManager.ACTION_SIP_MESSAGE_SYS);
		filter.addAction(SipManager.ACTION_SIP_KEEPALIVE);
		filter.addAction(SipManager.ACTION_NAT_KEEPALIVE_ERR);
		filter.addAction(SipManager.ACTION_NAT_ADDR_CHANGE);
		filter.addAction(SipManager.ACTION_SYS_NOTIFY);
		filter.addAction(SipManager.ACTION_SIP_NOTIFY_XCAP_DIFF);
		this.ctx.registerReceiver(this, filter,SipManager.PERMISSION_USE_SIP,null);


//		this.ctx.registerReceiver(this, new IntentFilter(SipManager.ACTION_SYS_PUBLISH));

//		this.ctx.registerReceiver( this, new IntentFilter(Intent.ACTION_LOCALE_CHANGED) );
//		if(Product.getProductType() != ProductConst.ProductType_NAPP_RADIO)
//		{
//			this.startTimer();
//		}
	}

	protected void setSysMsgListener(SysMsgListener sysMsgListener) {
		this.sysMsgListener = sysMsgListener;
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		Log.debug(this.getClass(), "Action is " + action);

		if (action.equals(SipManager.ACTION_SIP_STACK_CHANGED))
		{
			int svrState = intent.getIntExtra(SipManager.SIPSTACK_STATUS,-1);
			Log.debug(this.getClass(), "onReceive ACTION_SIP_STACK_CHANGED status is " + svrState);
			if(svrState == -1)
			{
				return;
			}
			if(SipManager.SIPSTACK_START == svrState)
			{
				sysAgent.recevSysMsg(SysConst.SysMsg_Svr_Start);
			}
			else if(SipManager.SIPSTACK_STOP == svrState)
			{
				sysAgent.recevSysMsg(SysConst.SysMsg_Svr_Stop);
			}
		}
		else if(action.equals(SipManager.ACTION_SIP_REG))
		{
			int code = intent.getIntExtra(SipManager.RESULT_CODE,0);//.getStringExtra(SipManager.RESULT_NAME);//intent.getFlags();
			String num = intent.getStringExtra(SipManager.RESULT_NUM);
			String name = intent.getStringExtra(SipManager.RESULT_NAME);
			Log.debug(this.getClass(), "onReceive ACTION_SIP_REG code = " + code + " num = " + num  + " name = " + name);
			sysAgent.onSipRegResult(code,name,num);
		}
		else if(action.equals(SipManager.ACTION_SIP_UNREG))
		{
			int code = intent.getIntExtra(SipManager.RESULT_CODE,0);//.getStringExtra(SipManager.RESULT_NAME);//intent.getFlags();
			String num = intent.getStringExtra(SipManager.RESULT_NUM);
			Log.debug(this.getClass(), "onReceive ACTION_SIP_REG code = " + code + " num = " + num  );
			sysAgent.onSipUnRegResult(code,num);
		}
		else if(action.equals(SipManager.ACTION_SIP_PUBLISH))
		{
			int code = intent.getIntExtra(SipManager.RESULT_CODE,0);
			int mcType = intent.getIntExtra(SipManager.RESULT_MCTYPE, CallAttr.McType_McPtt);
			Log.debug(this.getClass(), "onReceive ACTION_SIP_PUBLISH mcType = " + mcType);
			sysAgent.onPublishResult(code,mcType);
		}
		else if(action.equals(SipManager.ACTION_SIP_SUBSCRIBE))
		{
			int code = intent.getIntExtra(SipManager.RESULT_CODE,0);
			int mcType = intent.getIntExtra(SipManager.RESULT_MCTYPE, CallAttr.McType_McPtt);
			Log.debug(this.getClass(), "onReceive ACTION_SIP_SUBSCRIBE mcType = " + mcType);
			sysAgent.onSubscribeResult(code,mcType);
		}
		else if( action.equals(SipManager.ACTION_SIP_KEEPALIVE) )
		{
			if(sysAgent != null)
			{
				sysAgent.doKeepAlive(true);
			}
		}
		else if( action.equals(SipManager.ACTION_NAT_KEEPALIVE_ERR) )
		{
			/*String err = Resource.getString("e_nat_keepalive_failed");
			CommDlg.showToast(context, err);
			if(sysAgent != null)
			{
				sysAgent.doForceDetach();
			}*/
			if(sysMsgListener != null)
			{
				sysMsgListener.receiveSysMsg(SysConst.SysMsg_NAT_KEEPALIVE_ERR);
			}
		}
		else if( action.equals(SipManager.ACTION_NAT_ADDR_CHANGE) )
		{
			/*String err = Resource.getString("e_nat_keepalive_failed");
			CommDlg.showToast(context, err);
			if(sysAgent != null)
			{
				sysAgent.doForceDetach();
			}*/
			if(operator != null)
			{
				try {
					operator.restart();
				}catch (Exception e)
				{
					e.printStackTrace();
					Log.debug(this.getClass(), "onReceive ACTION_NAT_ADDR_CHANGE  e = " + e);
				}
			}
		}
		else if( action.equals(SipManager.ACTION_SIP_FOREDETACH) )
		{
			Log.debug(this.getClass(), "onReceive ACTION_SIP_FOREDETACH");
			if(sysAgent != null)
			{
				sysAgent.doForceDetach();
			}
		}
		else if( action.equals(SipManager.ACTION_SIP_SVR_RESTART) )
		{
			Log.debug(this.getClass(), "onReceive ACTION_SIP_SVR_RESTART");
			if(sysAgent != null)
			{
				sysAgent.doSvrRestart();
			}
		}
		else if( action.equals( SipManager.ACTION_SIP_NOTIFY_XCAP_DIFF ) )
		{
			String bodyStr = intent.getStringExtra(SipManager.Body_Str);
			Log.debug(this.getClass(), "onReceive ACTION_SIP_NOTIFY_XCAP_DIFF bodyStr = " + bodyStr);
			if( this.configCenter != null
					&& config != null
					&& bodyStr != null
					&& bodyStr.length() > 0)
			{
				int mcType = getMcTypeByBody(bodyStr);
				Log.debug(this.getClass(), "onReceive ACTION_SIP_NOTIFY_XCAP_DIFF mcType = " + mcType);
//				if(mcType == CallAttr.McType_McPtt)
//				{
				String cmsUrl = config.getBootStrapSvr().toCmsHttpUrl();
				String gmsUrl = config.getBootStrapSvr().toGmsHttpUrl();
				configCenter.recvNotify(cmsUrl,gmsUrl,bodyStr, this);
//				operator.subcribeCms(CallAttr.McType_McVideo);
//				}
//				else if(mcType == CallAttr.McType_McVideo)
//				{
//					operator.subcribeCms(CallAttr.McType_McData);
//				}
//				else if(mcType == CallAttr.McType_McData)
//				{
////					List<GroupInfo> list = dbAdapter.getGroupInfoList();
////					Log.debug(this.getClass(), "procNextSubcribeCmsGms list = " + list);
////					if(list != null
////							&& list.size() > 0) {
////						String[] groupIdArray = new String[list.size()];
////						int i = 0;
////						for (Iterator<GroupInfo> iterator = list.iterator(); iterator.hasNext();)
////						{
////							GroupInfo info = iterator.next();
////							groupIdArray[i] = info.getGroupId();
////						}
////						operator.subcribeGms(groupIdArray);
////					}
//				}
			}
		}
		else if(intent.getAction().equals(SipManager.ACTION_SIP_MESSAGE_SYS)) //鎺ュ彈鐭秷鎭箍鎾�
		{
			String bodyStr = intent.getStringExtra(SipManager.Body_Str);
			Log.debug(this.getClass(), "onReceive ACTION_SIP_MESSAGE_SYS bodyStr = " + bodyStr);
			if( bodyStr != null
					&& bodyStr.length() > 0) {
				try {
					McxExtensionXml xml = McxExtensionXml.parseXmlStr(bodyStr);
					Log.debug(this.getClass(), "onReceive ACTION_SIP_MESSAGE_SYS xml = " + xml);
					if(xml != null) {
						String msgType = xml.getMsgType();
						if(sysMsgListener != null)
						{
							sysMsgListener.receiveSysMsg(msgType);
						}
					}

				}catch (Exception e)
				{

				}
			}
		}
	}

	private int getMcTypeByBody(String bodyStr)
	{
		if(bodyStr.contains(UserProfile.FileName_Mcvideo))
		{
			return CallAttr.McType_McVideo;
		}
		else if(bodyStr.contains(UserProfile.FileName_Mcdata))
		{
			return CallAttr.McType_McData;
		}
		else
		{
			return CallAttr.McType_McPtt;
		}
	}



	public void clearResource()
	{
		Log.debug(this.getClass(), "SysBroadcast clearResource");
//		this.sysListener = null;
		this.sysMsgListener = null;
//		this.loginListener = null;
//		this.config.clearUserInfoAfterExit();
//		this.config  = null;
//		this.stopTimer();
		this.ctx.unregisterReceiver(this);
		this.ctx = null;
	}

	public void clearResourceForLogout()
	{
		Log.debug(this.getClass(), "SysBroadcast clearResourceForLogout");
//		this.curGoupSize = 0;
//		this.config.clearUserInfoAfterLogout();
	}

	@Override
	public void parserFileSuc(String fileName) {
		Log.debug(this.getClass(), "SysBroadcast parserFileSuc fileName = " + fileName);
		if(UserProfile.FileName_Mcptt.equals(fileName))
		{
			List<GroupInfo> list = dbAdapter.getGroupInfoList();
			int size = list.size();
			Log.debug(this.getClass(), "procNextSubcribeCmsGms list.size() = " + list.size() + " size = " + size + " list = " + list);
//			if(curGoupSize != size)
//			{
//				curGoupSize = size;
				doSubscribeGms(list);
//			}
		}
	}


	@Override
	public void parserFileFailed(String fileName, String errStr) {
		Log.debug(this.getClass(), "SysBroadcast parserFileFailed fileName = " + fileName + " errStr = " + errStr);
	}

	private void procNextSubcribeCmsGms(String fileName)
	{
		Log.debug(this.getClass(), "procNextSubcribeCmsGms fileName = " + fileName);
	}

	public void doSubscribeGms(List<GroupInfo> list)
	{
		Log.debug(this.getClass(), "doSubscribeGms list.size() = " + list.size() + " list = " + list);
		if (list != null
				&& list.size() > 0) {
//			curGoupSize = list.size();
			String[] groupIdArray = new String[list.size()];
			int i = 0;
			for (Iterator<GroupInfo> iterator = list.iterator(); iterator.hasNext(); ) {
				GroupInfo info = iterator.next();
				groupIdArray[i] = info.getGroupId();
				i++;
			}
			McIdInfo idInfo = config.getMcpttLoginInfo().getMcIdInfo();//teke
			String accessToken = idInfo.getAccessToken();
			operator.subcribeGms(groupIdArray,accessToken);
		}
	}
}


